package edu.spec.chenli.Listener;

import edu.spec.chenli.Servlet.DbDao;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.ResultSet;

//@WebListener()
public class RequestListener implements ServletRequestListener{


    public void requestDestroyed(ServletRequestEvent sre) {

    }

    public void requestInitialized(ServletRequestEvent sre) {
        HttpServletRequest request= (HttpServletRequest) sre.getServletRequest();
        HttpSession session=request.getSession();
        //获取sessionID
        String sessionId=session.getId();
        //获取访问的IP和正在访问的页面
        String ip=request.getRemoteAddr();
        String page=request.getRequestURI();
        String user= (String) request.getAttribute("user");
        //为登录用户当游客处理
        user=(user==null)?"游客":user;
        try {
        DbDao dd=new DbDao("com.mysql.jdbc.Driver","jdbc:mysql://localhost:3306/1613580007_1",
                "root","123456789");
        ResultSet rs= null;

            rs = dd.query("select * from online_inf where session_id=?",true,sessionId);
            //如果该用户对应的session ID 存在，表面是旧的会话

            if(rs.next()){
                //更新记录
                rs.updateString(4,page);
                rs.updateLong(5,System.currentTimeMillis());
                rs.updateRow();
                rs.close();
            }
            else {
                //插入该用户的在线信息
                dd.insert("insert into online_inf values(?,?,?,?,?)", sessionId, user, ip, page, System.currentTimeMillis());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
